package com.insmess.speech.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.insmess.speech.common.constant.PathConstant;
import com.insmess.speech.dto.SpeechConfigDto;
import com.insmess.speech.service.ConfigService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.Map;
import java.util.Properties;

@Service
@Slf4j
public class LocalConfigServiceImpl implements ConfigService {

    private String insmessSpeechConfigPath;

    @PostConstruct
    public void init() {
        initConfig();
    }

    @SneakyThrows
    @Override
    public void set(SpeechConfigDto speechConfigDto) {
        try (Writer w = new FileWriter(insmessSpeechConfigPath)) {
            String jsonStr = JSONUtil.toJsonStr(speechConfigDto);
            w.write(jsonStr);
            log.info("配置文件修改：{}", jsonStr);
        }
    }

    @SneakyThrows
    @Override
    public void initConfig() {
        insmessSpeechConfigPath = PathConstant.INSMESS_SPEECH_PATH + File.separator + "conf" + File.separator + "insmess-speech-conf.json";
        File confFile = new File(insmessSpeechConfigPath);
        if (!confFile.getParentFile().exists()) {
            confFile.getParentFile().mkdirs();
        }
        if (confFile.exists()) {
            log.info("配置文件已存在：{}", insmessSpeechConfigPath);
        } else {
            //创建配置文件
            SpeechConfigDto speechConfigDto = new SpeechConfigDto();
            String jsonStr = JSONUtil.toJsonStr(speechConfigDto);
            try (Writer w = new FileWriter(insmessSpeechConfigPath)) {
                w.write(jsonStr);
                log.info("配置文件初始化完成：{}", insmessSpeechConfigPath);
            }
        }
    }

    @SneakyThrows
    @Override
    public SpeechConfigDto get() {
        String json = FileUtils.readFileToString(new File(insmessSpeechConfigPath), "utf-8");
        SpeechConfigDto speechConfigDto = JSONUtil.toBean(json, SpeechConfigDto.class);
        return speechConfigDto;
    }
}
